#include "../serial/serial.h"
#include <queue>
#include <mutex>
#include <condition_variable>
#include <atomic>
#include <thread>
#include <iostream>


// 全局变量，用于在主线程和串口线程之间共享数据
extern std::atomic<bool> running;
extern std::queue<ReceivedData> receivedDataQueue;
extern std::mutex dataQueueMutex;
extern std::condition_variable dataQueueCond;

void serialThreadFunc(Serial& serial) {
    // 检查是否为虚拟串口模式
    if (serial.isVirtual()) {
        std::cout << "Virtual serial mode: serial thread not needed" << std::endl;
        return;
    }

    while (running.load()) {
        ReceivedData data;
        if (serial.readData(data)) {
            // 加锁并更新队列，保持队列长度为1
            {
                std::lock_guard<std::mutex> lock(dataQueueMutex);
                if (!receivedDataQueue.empty()) {
                    receivedDataQueue.pop(); // 移除旧数据
                }
                receivedDataQueue.push(data); // 添加新数据
            }
            dataQueueCond.notify_one();
        }
    }
}
